<?php

namespace app\web\service;

use app\common\model\commonModel;
use app\common\model\trInvoices;
use app\common\model\trOrder;
use app\common\util\ErrorCode;

/**
 * Class Auth
 * @package app\admin\service
 * 发票服务类
 */
class InvoiceService
{
    private $field = [
        "user_id" => "0", "order_sn" => "require", "type" => 1, "head_name" => "require", "duty_number" => "",
        "money" => "0", "mobile" => "", "address" => ""
    ]; //填入数据库需要存储的表字段
    private $fieldMsg = [
        "order_sn" => "订单编号", "head_name" => "发票抬头",
    ];
    private $data = [];
    private $returnData;
    private $params;

    public function __construct($data, $params)
    {
        $this->returnData = $data;
        $this->params = $params;
    }

    // 获取发票数据的分页列表
    public function getList(){
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;

        $model = new trOrder();
        $data = $model->getList("order_sn as id,pay_money,address_from,address_to,reserve_time", [
            "invoice" => 0, "user_id" => request()->userLoginData["id"], "status" => 8
        ], $page, $pageSize); // 筛选没开票的
        $base = $model->getFields("pay_money", ["invoice" => 0, "user_id" => request()->userLoginData["id"], "status" => 8], false); // 筛选没开票的
        $totalMoney = 0;
        if(!empty($base)){
            foreach ($base as $item){
                $totalMoney += $item["payMoney"];
            }
        }
        if(!$data["data"]){
            $this->returnData['data'] = ['list' => [], 'totalMoney' => $totalMoney, 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        }else {
            $this->returnData['data'] = ['list' => $data['data'], 'totalMoney' => $totalMoney, 'totalPage' => $data['last_page'], 'currentPage' => $data['current_page'], 'count' => $data['total']];
        }
        return $this->returnData;
    }

    // 添加发票
    public function toAdd(){
        foreach ($this->field as $k => $v) {
            $ks = parse_name($k); //转换字段，变驼峰
            if($v === 'require' && !isset($this->params[$ks])){
                return ErrorCode::code("params_not_exist", $this->fieldMsg[$k]);
            }
            $this->data[$k] = isset($this->params[$ks]) ? $this->params[$ks] : $v;
        }
        $this->data["user_id"] = request()->userLoginData["id"];
        $this->data["mall_id"] = request()->mallData["id"];
        $orderModel = new trOrder();
        $model = new trInvoices();
        if(strtolower($this->params["orderSn"]) == "all"){ // 所有订单开发票
            $this->data["money"] = 0;
            $data = $orderModel->getFields("pay_money", ["invoice" => 0, "user_id" => request()->userLoginData["id"], "status" => 8], false); // 筛选没开票的
            foreach ($data as $item){
                $this->data["money"] += $item["payMoney"];
            }
        }else {
            $this->data["money"] = $orderModel->getValue("pay_money", ["order_sn" => $this->params["orderSn"], "status" => 8]);
        }
        if($this->data["money"] <= 0){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "发票价格有误";
            return $this->returnData;
        }
        $result = $model->add($this->data, true);
        if(isset($result["code"])) {
            return $result;
        }
        if(!$result){
            $this->returnData = ErrorCode::$errorCode["fail"];
        }
        if(!commonModel::getCount(personalInvoiceTable, ["user_id" => request()->userLoginData["id"], "type" => $this->data["type"], "head_name" => $this->data["head_name"]])) {
            commonModel::toAdd(personalInvoiceTable, [
                "user_id" => request()->userLoginData["id"], "type" => $this->data["type"], "head_name" => $this->data["head_name"],
                "duty_number" => isset($this->data["duty_number"]) ? $this->data["duty_number"] : null,
                "create_time" => time(), "mall_id" => request()->mallData["id"]
            ]);
        }
        if(strtolower($this->params["orderSn"]) == "all") {
            $orderModel->doUpdate(["invoice" => $result], ["invoice" => 0, "user_id" => request()->userLoginData["id"], "status" => 8]);
        }else {
            $orderModel->doUpdate(["invoice" => $result], ["order_sn" => $this->params["orderSn"], "status" => 8]);
        }
        return $this->returnData;
    }

    public function getHistory(){
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;

        $model = new trOrder();
        $data = $model->getList("invoice as id,order_sn,address_from,address_to,reserve_time,pay_money", [
            ["invoice", "<>", 0], ["user_id", "=", request()->userLoginData["id"]]
        ], $page, $pageSize); // 筛选没开票的
        if(!$data["data"]){
            $this->returnData['data'] = ['list' => [], 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        }else {
            $invoiceModel = new trInvoices();
            foreach ($data["data"] as $k => $item){
                if(empty($invoiceData[$item["id"]])){
                    $invoiceData[$item["id"]] = $invoiceModel->getValue("status", ["order_sn" => $item["orderSn"]], 1);
                }
                $data["data"][$k]["invoiceStatus"] = $invoiceData[$item["id"]];
            }
            $this->returnData['data'] = ['list' => $data['data'], 'totalPage' => $data['last_page'], 'currentPage' => $data['current_page'], 'count' => $data['total']];
        }
        return $this->returnData;
    }

    // 发票的详细内容
    public function getDetail(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $model = new trInvoices();
        $data = $model->getFields("*", ["id" => $this->params["id"]]);
//        if($data["orderSn"] == "all"){
//            $orderModel = new trOrder();
//            $this->data["money"] = 0;
//        }
        $this->returnData["data"] = $data;
        return $this->returnData;
    }
}